﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Genuilder.Extensibility
{
	public abstract class GenItemCollectionBase : IEnumerable<GenItem>
	{
		protected abstract ExecutionContext ExecutionContext
		{
			get;
		}
		protected abstract GenItem Owner
		{
			get;
		}
		protected abstract GenItemRepository Repository
		{
			get;
		}

		public IEnumerable<GenItem> GetByNames(params string[] files)
		{
			return GetByQuery(new FileQuery().SelectByNames(files));
		}

		public IEnumerable<GenItem> GetByQuery(FileQuery query)
		{
			foreach(var item in this)
			{
				if(query.CanFetch(item.SourceFile))
					yield return item;
			}
		}

		public GenItem CreateNew(string name)
		{
			return CreateNew(new SourceFile(name, SourceType.Compile));
		}
		public GenItem CreateNew(string name, SourceType sourceType)
		{
			return CreateNew(new SourceFile(name, sourceType));
		}
		public GenItem CreateNew(SourceFile sourceFile)
		{
			sourceFile = new SourceFile(ExecutionContext.StartInfo.CreateGeneratedChildName(sourceFile.Name), sourceFile.SourceType);
			var child = this.CreateOrChangeParent(sourceFile);
			child.RecreateFile();
			return child;
		}

		protected GenItem CreateOrChangeParent(SourceFile child)
		{
			var file = Repository.Resolve(child);
			if(file == null)
			{
				file = ExecutionContext.Create(child, true);
				Repository.Register(file);
			}
			file.Children.ChangeParent(Owner);
			return file;
		}

		#region IEnumerable<GenItem> Members

		public abstract IEnumerator<GenItem> GetEnumerator();

		#endregion

		#region IEnumerable Members

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		#endregion
	}
}
